package com.ara.common.project.widget;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

import com.ara.common.project.R;

/**
 * Created by XieXin on 2021/5/12.
 * 标题栏
 */
public class TitleBar extends FrameLayout {
    private View view;
    private ImageView ivBack;
    private TextView tvTitle;
    private TextView tvRight;
    private OnClickListener backOnClickListener;
    private Activity activity;

    public TitleBar(@NonNull Context context) {
        this(context, null);
    }

    public TitleBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public TitleBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        view = inflate(context, R.layout.title_bar, this);
        init();
    }

    private void init() {
        ivBack = view.findViewById(R.id.ivBack);
        tvTitle = view.findViewById(R.id.tvTitle);
        tvRight = view.findViewById(R.id.tvRight);
    }

    public void setShowBack(boolean showBack) {
        if (ivBack != null) ivBack.setVisibility(showBack ? VISIBLE : GONE);
    }

    public void setTitle(@StringRes int resId) {
        if (tvTitle != null) tvTitle.setText(resId);
    }

    public void setTitle(String title) {
        if (tvTitle != null) tvTitle.setText(title);
    }

    public void setRightText(@StringRes int resId) {
        if (tvRight != null && resId != 0) {
            tvRight.setText(resId);
            tvRight.setVisibility(VISIBLE);
        }
    }

    public void setRightText(String title) {
        if (tvRight != null && !TextUtils.isEmpty(title)) {
            tvRight.setText(title);
            tvRight.setVisibility(VISIBLE);
        }
    }

    public void setBackFinish(Activity activity) {
        this.activity = activity;
        ivBack.setOnClickListener(v -> {
            if (this.activity != null) this.activity.finish();
        });
    }

    public void setBackOnClickListener(OnClickListener onClickListener) {
        this.backOnClickListener = onClickListener;
        ivBack.setOnClickListener(v -> {
            if (backOnClickListener != null) backOnClickListener.onClick(v);
        });
    }
}
